package com.ibeeking.found.msg.rest.service.impl;

import com.ibeeking.found.common.constants.WxMpConstant;

import com.ibeeking.found.common.enums.mp.WxMpSourceTypeEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IWxMpFansService;
import com.ibeeking.found.msg.rest.service.IWxMpSourceService;
import com.ibeeking.found.msg.rest.service.IWxMpMsgService;
import com.ibeeking.found.msg.rest.service.IOpenService;
import com.ibeeking.found.msg.service.common.bo.WxMpFansBO;
import com.ibeeking.found.msg.service.common.dos.WxMpFansDO;
import com.ibeeking.found.msg.service.common.dos.WxMpMsgDO;
import com.ibeeking.found.msg.service.common.param.WxMpAutoMsgParam;
import com.ibeeking.found.msg.service.common.param.WxMpMsgParam;
import com.ibeeking.found.msg.service.common.query.WxMpMsgPageQuery;
import com.ibeeking.found.msg.service.common.vo.WxMpSourceDetailVO;
import com.ibeeking.found.msg.service.common.vo.WxMpMsgVO;
import com.ibeeking.found.msg.service.common.vo.WxMpGroupMessageUploadVO;
import com.ibeeking.found.msg.service.common.vo.WxMpSourceVO;
import com.ibeeking.found.msg.service.mapper.WxMpMsgMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ibeeking.nematos.utils.data.Collections3;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class WxMpMsgServiceImpl extends ServiceImpl<WxMpMsgMapper, WxMpMsgDO> implements IWxMpMsgService {

    @Resource
    private WxMpMsgMapper wxMpMsgMapper;

    @Resource
    private IWxMpFansService wxMpFansServiceImpl;

    @Resource
    private IOpenService wxOpenServiceImpl;

    @Resource
    private IWxMpSourceService wxMpSourceServiceImpl;

    @Override
    public IPage<WxMpMsgVO> listWxMsgMapGroup(WxMpMsgPageQuery pageQuery) {
        Page<WxMpMsgDO> page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
        IPage<WxMpMsgVO> listIPage = this.wxMpMsgMapper.listWxMpMsgMapGroup(page, pageQuery);
        return listIPage;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object pageList(WxMpMsgPageQuery pageQuery) {
        Page<WxMpMsgVO> page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
        return this.wxMpMsgMapper.pageList(page, pageQuery);
    }

    @Deprecated
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxMpMsgVO add(WxMpMsgParam param) {
        try {
            Long tenantId = UserUtils.getTenantID();
            WxMpFansDO wxUser = wxMpFansServiceImpl.getById(param.getWxUserId());
            //入库
            param.setNickName(wxUser.getNickName());
            param.setHeadimgUrl(wxUser.getHeadImgurl());
            param.setType(WxMpConstant.WX_MSG_TYPE_2);
            WxMpKefuMessage wxMpKefuMessage = null;
            //wxMpKefuMessage = this.messageFoctry(param, wxMpKefuMessage);
            if (wxMpKefuMessage != null) {
                WxMpService wxMpService = wxOpenServiceImpl.getWxOpenMpService(tenantId);
                WxMpKefuService wxMpKefuService = wxMpService.getKefuService();
                wxMpKefuMessage.setToUser(wxUser.getOpenId());
                wxMpKefuService.sendKefuMessage(wxMpKefuMessage);
                WxMpMsgDO wxMsgDO = BeanUtil.convertBean(param, WxMpMsgDO.class);
                wxMsgDO.setCreateTime(LocalDateTime.now());
                wxMsgDO.setModifyTime(LocalDateTime.now());
                this.wxMpMsgMapper.insert(wxMsgDO);
                WxMpMsgVO wxMsgVO = BeanUtil.convertBean(param, WxMpMsgVO.class);
                return wxMsgVO;
            } else {
                throw new BusinessException("非法消息类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增微信消息失败" + e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        //return  null;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(WxMpMsgParam param) {
        Long userId = UserUtils.getUserId();
        WxMpMsgDO wxMpMsgDO = BeanUtil.convertBean(param, WxMpMsgDO.class);
        wxMpMsgDO.setModifyBy(userId);
        wxMpMsgDO.setModifyTime(LocalDateTime.now());
        return this.wxMpMsgMapper.updateById(wxMpMsgDO) > 0;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        return this.wxMpMsgMapper.deleteById(id) > 0;
    }

    @Override
    public WxMpGroupMessageUploadVO.Message view(Long id) {
        WxMpMsgDO wxMpMsgDO = this.wxMpMsgMapper.selectById(id);
        WxMpGroupMessageUploadVO.Message message = new WxMpGroupMessageUploadVO.Message();
        if(wxMpMsgDO ==null){
            return message;
        }
        message.setAppId(wxMpMsgDO.getAppId());
        if (WxMpConstant.MESSAGE_TEXT.equals(wxMpMsgDO.getReturnType())) {
            message.setUnionKey(wxMpMsgDO.getReturnContent());
            message.setSourceType(WxMpSourceTypeEnum.TEXT.getName());
        } else {
            message.setUnionKey(wxMpMsgDO.getRepMediaId());
            WxMpSourceVO wxMpSourceVO = this.wxMpSourceServiceImpl.queryByMediaId(wxMpMsgDO.getRepMediaId());
            if (wxMpSourceVO != null) {
                message.setSourceType(wxMpSourceVO.getSourceType());
                if (WxMpSourceTypeEnum.IMAGE_TEXT.getName().equals(wxMpSourceVO.getSourceType())) {
                    if (wxMpSourceVO != null) {
                        List<WxMpSourceDetailVO> wxMpSourceDetailVOS =  wxMpSourceVO.getSourceDetail();
                        if(Collections3.isNotEmpty(wxMpSourceDetailVOS)) {
                             message.setSourceDetails(wxMpSourceDetailVOS);
                        }
                    }
                } else {
                    message.setRepName(wxMpSourceVO.getName());
                    if (StringUtils.isNotBlank(wxMpSourceVO.getPath())) {
                        message.setRepUrl(wxMpSourceVO.getPath());
                    } else {
                        message.setRepUrl("");
                    }
                }
            }
        }

        return message;
    }

    //@Async
    @Override
    @Transactional(noRollbackFor = Throwable.class)
    public void add(WxMpAutoMsgParam param) {
        Long userId = UserUtils.getUserId();
        if (param == null) {
            return;
        }
        WxMpMsgDO wxMpMsgDO = new WxMpMsgDO();
        try {
            wxMpMsgDO.setAppId(param.getAppId());
            WxMpFansBO wxMpFans = wxMpFansServiceImpl.queryByAppIdAndOpenId(param.getAppId(), param.getOpenId());
            if (wxMpFans != null) {
                wxMpMsgDO.setWxUserId(wxMpFans.getId().toString());
            }
            wxMpMsgDO.setRepType(param.getRepType());
            wxMpMsgDO.setRepEvent(param.getRepEvent());
            wxMpMsgDO.setReturnType(param.getReturnType());
            wxMpMsgDO.setRepContent(param.getRepContent());
            if (WxMpConstant.MESSAGE_TEXT.equals(param.getReturnType())) {
                wxMpMsgDO.setReturnContent(param.getUnionKey());
            } else {
                wxMpMsgDO.setRepMediaId(param.getUnionKey());
            }
            wxMpMsgDO.setCreateBy(userId);
            wxMpMsgDO.setModifyBy(userId);
            wxMpMsgDO.setCreateTime(LocalDateTime.now());
            wxMpMsgDO.setModifyTime(LocalDateTime.now());
            this.wxMpMsgMapper.insert(wxMpMsgDO);
        } catch (Exception e) {
            LogUtils.error("自动回复消息记录保存失败。公众号id :[{}] , 粉丝openId : [{}] , 消息类型 : [{}] , 回复消息类型 : [{}] , 事件类型 : [{}] , 回复内容 : [{}]",
                    param.getAppId(), param.getOpenId(), param.getRepType(), param.getReturnType(), param.getRepEvent(), param.getUnionKey());
        }


    }




}
